﻿var $url = new Url();
var dict = new Dict();//字典信息
var $Id = $url.GetQueryString("orderId");
var serializer = new JSONSerializer();

//绑定对应数据
$(function () {
    //绑定代扣银行列表
    var getPayBank = dict.GetDictDDLByType(12);
    $(".ddlPayBank").html(getPayBank);

    //绑定划付银行列表
    var getTransferBank = dict.GetDictDDLByType(15);
    $(".ddlTransferBank").html(getTransferBank);

    //默认划付隐藏
    $(".transferBank").css("display", "none");

    //根据划收和划付银行是否一致来隐藏显示划付信息
    $("input[type='radio'][name=IsSameBank]").click(function () {
        var $IsSameBank = $(this).val();
        if ($IsSameBank === "false") {
            $(".transferBank").css("display", "block");
        }
        else {
            $(".transferBank").css("display", "none");
        }
    });
    if (!$Id) {//添加新订单
        $(".lblUserName").css("display", "none");
        $(".txtUserName").focus(function () { $(".btnShow").click() });
    }
    else {//编辑订单
        $(".txtUserName,.btnShow,.validateCode,#btnSendCaptcha").css("display", "none");
        $(".txtTel,.txtIDCard").attr("disabled", "disabled");
        var userId = $(".hdUserId").val();
        $.getJSON(
                "../Handler/FinancialOrder.ashx",
                { Id: $Id, type: 4, _: Math.random(), "UserId": userId },
                function (result) {
                    if (result.Status) {
                        $(".txtCaptcha").val(1);
                        serializer.DeSerialize($("#orderInfo")[0], result.Data.Order);
                        $(".txtContractStartDate").val(result.Data.Order.ContractStartDate);
                        $(".txtContractEndDate").val(result.Data.Order.ContractEndDate);
                        $(".txtInitialLoanDate").val(result.Data.Order.InitialLoanDate);
                        //划扣、划付银行不一致，显示划付开户行（精确到支行）
                        if (!result.Data.Order.IsSameBank) {
                            $('input:radio[name=IsSameBank]:nth(1)').click();
                        }
                        //是否家庭计划
                        if (result.Data.Order.IsFortunePlan) {
                            $('input:radio[name=IsFortunePlan]:eq(0)').click();
                        }
                        //是否福盈计划
                        if (result.Data.Order.IsFuinn) {
                            $('input:radio[name=IsFuinn]:eq(0)').click();
                            $(".txtCMName").val(result.Data.Order.CMName);
                        }
                        $(".progressBar").text(result.Data.Order.Done + "%").css("width", result.Data.Order.Done + "%");
                        if (result.Data.Order.Done >= 50) {
                            $(".OrderId").val(result.Data.Order.OrderId);
                            if (result.Data.Order.Done == 100) {
                                $(".submit").show();
                            }
                        }
                        if (result.Data.User) {//如果订单对应的用户信息存在
                            $(".lblUserName").text(result.Data.User.Name);
                            $(".txtUserName").val(result.Data.User.Name);
                            $(".hdUserId").val(result.Data.User.UserId);
                            serializer.DeSerialize($("#userInfo")[0], result.Data.User);
                            var userId = result.Data.User.UserId;
                            $.ajax({
                                url: "../Handler/FinancialOrder.ashx",
                                type: "post",
                                data: { "type": 31, "UserId": userId, "OrderId": $Id },
                                dataType: 'json',
                                cache: false,
                                success: function (result) {
                                    if (result.Status) {
                                        var sumAmount = result.Data.SumAmount;
                                        if (($("#ddlFProduct option:selected").val() == 1 || $("#ddlFProduct option:selected").val() == 2) && parseFloat(sumAmount) >= 100) {
                                            $('.link_man_t').css('display', 'block');
                                            $("#title_fold_next1").slideDown(500);
                                            if (result.Data.AlreadyRelatedAmount == 0) { $("#profitGroup").css('display', 'none'); }
                                            else { $("#profitGroup").css('display', 'block'); }
                                            ////可绑定年度产品订单(1..)
                                            $("#spanbutProductshow").text(result.Data.OrderIds);
                                            //所关联订单跳点基数
                                            $("#spanRelatedSumJumpProfit").text(result.Data.AlreadyRelatedAmount == 0 ? "" : result.Data.AlreadyRelatedAmount + "万元");
                                            //所关联订单重叠区间
                                            $("#spanRelatedOrderRange").text(result.Data.RelatedOrderRange);
                                        }
                                        if (($("#ddlFProduct option:selected").val() != 1 && $("#ddlFProduct option:selected").val() != 2) || parseFloat(sumAmount) < 100) {
                                            $('.link_man_t').css('display', 'none');
                                        }
                                    }
                                }
                            });
                        }
                        if (result.Data.UserEmgy) {
                            serializer.DeSerializeToSpan($("#title_fold_next"), result.Data.UserEmgy);
                        }
                        //当前订单理财规模
                        $(".OrderAmount").text($(".txtAmount").val() + "万元");
                    }
                    else {
                        alert(result.Message);
                    }
                }
            );
    }
})
//
$(':input[name="IsFuinn"]').click(function () {
    var valCheck = $(this).val();
    if (valCheck == "true") {
        $(".divCMName").show();
        $(".txtCMName").addClass("text").removeClass("NonSerialized");
    }
    else {
        $(".divCMName").hide();
        $(".txtCMName").removeClass("text").addClass("NonSerialized");
        $(".txtCMName").next("span").text("");
    }
});

//取得.modal-body相关表单元素
var $BackAccountName = $(".txtBackAccountName");
var $BackAccountNum = $(".txtBackAccountNum");
var $BackName = $(".txtBackBankName");
var $BackBranchBankName = $(".txtBackBranchBankName");
//预防多次提交保存的表单
var $CheckSubmitFlg = false;
//保存
$(".save").click(function () { 
    if ($CheckSubmitFlg == true) { $CheckSubmitFlg = false; return false; }
    $CheckSubmitFlg = true;
    var errorNode = null;
    //划扣、划付银行是否一致 不序列化划付银行信息
    if ($("input:radio[name=IsSameBank]")[0].checked) {
        $("div.transferBank  [name]").removeClass("text").addClass("NonSerialized");
    } else {
        $("div.transferBank  [name]").addClass("text").removeClass("NonSerialized");
    }
    $("#liFinaInfo .text").each(function () {
        if (!$(this).val() || $(this).val() == -1) {
            errorNode = $(this);
            $name = $(this).attr("data-name");
            $(this).next("span").text($name + "不能为空！");
            $(this).focus();
            $CheckSubmitFlg = false;
            return false;
        }
    });
    if (errorNode) {
        return;
    }
    var validate = new Validate();
    var msg = new Array("验证通过", "非法身份证号", "非法地区", "非法生日");
    if ($(".txtCertificateType").val() == "身份证") {
        var i = validate.CheckIdCard($(".txtIDCard").val());
        if (i < 0) {
            $(".txtIDCard").focus();
            $(".errorIDCard").text(msg[Math.abs(i)]);
            return;
        }
    }
    if (!validate.CheckNumber($(".txtAmount").val())) {
        $(".txtAmount").focus();
        $(".errorAmount").text("请输入正确的数字格式 .例如：100,100.11"); //判断只能输入 大于0的整数或小数 正则表达式
        return;
    }
    if (!validate.CheckNumber($(".txtIncome").val())) {
        $(".txtIncome").focus();
        $(".errorIncome").text("请输入正确的数字格式 .例如：100,100.11"); //判断只能输入 大于0的整数或小数 正则表达式
        return;
    }
    if (!validate.CheckNum($(".txtTerm").val())) {
        $(".txtTerm").focus();
        $(".errorTerm").text("不是数字格式")//数字验证
        return;
    }
    if (!$Id && $(".txtCaptcha ").val() != '') {//添加的时候校验验证码
        if (validateCode() <= 0) {
            $(".errorCaptcha").text("验证码错误！");
            return;
        }
    }
    var serializer = new JSONSerializer();
    var $formData = serializer.Serialize($("#formData")[0]);
    $formData._ = Math.random();
    $formData.type = $Id ? 2 : 1;

    $formData.IsSameBank = $('input:radio[name=IsSameBank]:checked').val();
    $formData.IsFortunePlan = $('input:radio[name=IsFortunePlan]:checked').val();
    $formData.IsFuinn = $('input:radio[name=IsFuinn]:checked').val();
    if ($Id && !isNaN($Id)) {
        $formData.OrderId = $Id;
    }
   
    $.getJSON(
        "../Handler/FinancialOrder.ashx",
        $formData,
        function (result) {
            if (result.Status) {
                $(".progressBar").text("50%").css("width", "50%");
                $(".NewOrderId").val(result.Data);//隐藏域订单ID赋值
                $(".OrderId").val(result.Data);
                alert(result.Message);
                if ($("#ddlFProduct option:selected").val() != 1 && $("#ddlFProduct option:selected").val() != 2) {
                    $("li:contains('手续上传')").click();
                }
                if (!$Id) {
                    $Id = result.Data;
                }
                var userId = $(".hdUserId").val();
                $CheckSubmitFlg = false;
                $.ajax({
                    url: "../Handler/FinancialOrder.ashx",
                    type: "post",
                    data: { "type": 31, "UserId": userId, "OrderId": $Id },
                    dataType: 'json',
                    cache: false,
                    success: function (result) {
                        if (result.Status) {
                            if ($formData.type == 2) {
                                $.ajax({
                                    url: "../Handler/FinancialOrder.ashx",
                                    type: "post",
                                    data: { type: 37, "id": $Id, _: Math.random() },
                                    dataType: 'json',
                                    cache: false,
                                    success: function (result) {}
                                });
                            }
                            if (($("#ddlFProduct option:selected").val() == 1 || $("#ddlFProduct option:selected").val() == 2) && parseFloat(result.Data.SumAmount) >= 100) {
                                $('.link_man_t').css('display', 'block');
                                $("#title_fold_next1").slideDown(500);
                                if (result.Data.AlreadyRelatedAmount == 0) { $("#profitGroup").css('display', 'none'); }
                                else { $("#profitGroup").css('display', 'block'); }
                                ////可绑定年度产品订单(1..)
                                $("#spanbutProductshow").text(result.Data.OrderIds);
                                //所关联订单跳点基数
                                $("#spanRelatedSumJumpProfit").text(result.Data.AlreadyRelatedAmount == 0 ? "" : result.Data.AlreadyRelatedAmount + "万元");
                                //所关联订单重叠区间
                                $("#spanRelatedOrderRange").text(result.Data.RelatedOrderRange);
                            }
                            if ($formData.type == 2) {
                                $("#profitGroup").css('display', 'none');
                            }
                            if (($("#ddlFProduct option:selected").val() != 1 && $("#ddlFProduct option:selected").val() != 2) || parseFloat(result.Data.SumAmount) < 100) {
                                $('.link_man_t').css('display', 'none');
                                $("li:contains('手续上传')").click();
                            }
                        }
                        else {
                            alert(result.Message);
                        }
                    }
                });
            }
            else {
                alert(result.Message);
                $CheckSubmitFlg = false;
                window.location.reload();
            }
        }
    );
    $CheckSubmitFlg = false;
    $(".OrderAmount").text($(".txtAmount").val() + "万元");
});
//提交
$(".submit").click(function () {
    var orderId = $(".OrderId").val();
    if (orderId && orderId > 0) {
        if ($(".completelist tr[id]").length > 0) {
            if ($("#fileBinded").val()) {
                $.getJSON("../Handler/FinancialOrder.ashx", { type: 10, OrderId: orderId, _: Math.random() }, function (result) {
                    alert(result.Message);
                    if (result.Status) {
                        window.location.href = "BorrowStatics.aspx?css=1020";
                    }
                });
            }
            else {
                alert("请先上传文件！");
            }
        }
        else {
            alert("请先上传文件！");
        }
    }
    else {
        $("li:contains('项目')").click();
        alert("请先保存订单!");
    }
    return false;
});
//预览
$(".detail").click(function () {
    var $formData = serializer.Serialize($("#formData"));
    $("#previewArea span[data-name]").each(function (index, item) {
        $(this).text($formData[$(this).attr("data-name")]);
    });
    $("#previewArea span[data-name=UserName]").text($(".lblUserName").text());
    //$("#previewArea span[data-name=UserGrade]").text($(".ddlUserGrade option[value='" + $(".ddlUserGrade").val() + "']").text());
    $("#previewArea span[data-name=PTypeId]").text($(".ddlFProduct option[value='" + $(".ddlFProduct").val() + "']").text());
    $("#previewArea span[data-name=ContractStartDate]").text($("#previewArea span[data-name=ContractStartDate]").text().substring(0, 10));
    $("#previewArea span[data-name=ContractEndDate]").text($("#previewArea span[data-name=ContractEndDate]").text().substring(0, 10));
    $("#previewArea span[data-name=InitialLoanDate]").text($("#previewArea span[data-name=InitialLoanDate]").text().substring(0, 10));
});
//change事件
$(".text").change(function () {
    $(this).next("span").empty();
});

$(".getdate").change(function () {
    $(this).parent().next().next().empty();
})


$(".modal-body .txtFinaOrderId").change(function () {
    var errorNode = null;
    var value = $(this).val();
    if (value == "" || value == -1) {
        $name = $(this).attr("data-name");
        errorNode = $(this);
        $(this).next("span").text($name + "不能为空！");
        $(this).focus();
        return false;
    }
    if (errorNode) {
        return;
    }
});

$BackAccountName.change(function () {
    if ($BackAccountName.val() == "") {
        $BackAccountName.next("span").text($BackAccountName.attr("data-name") + "不能为空");
        return false;
    }
});
$BackAccountNum.change(function () {
    var validate = new Validate();
    if (!validate.CheckNum($(".txtBackAccountNum").val())) {
        $(".txtBackAccountNum").focus();
        $(".txtBackAccountNum").next("span").text("请输入正确的数字格式 .例如：100");
        //$(".errorBackAccountNum").text("不是数字格式")//数字验证
        return;
    }
});
$BackBranchBankName.change(function () {
    if ($BackBranchBankName.val() == "") {
        $BackBranchBankName.next("span").text($BackBranchBankName.attr("data-name") + "不能为空");
        return false;
    }
});
$BackName.change(function () {
    if ($BackName.val() == "") {
        $BackName.next("span").text($BackName.attr("data-name") + "不能为空");
        return false;
    }
})

//搜索
//客户查找
$(".btnSearch").click(function () {
    var $userName = $(".txtName").val();
    var $phone = $(".txtPhone").val();
    $.getJSON("../Handler/FinancialUser.ashx",
        { UserName: $userName, Phone: $phone, CreateUser: true, type: 10, _: Math.random() },
        function (result) {
            if (result.Status) {
                $(".userInfo").empty();
                $(result.Data).each(function (index, item) {
                    $("#UserTemplete").tmpl(item).appendTo($(".userInfo"));
                });
                $(".userInfo tr").css("cursor", "pointer").click(function () {
                    var userId = $(this).find(".userId").text();
                    $(".txtUserName").val($(this).find(".name").text());
                    $(".lblUserName").text($(this).find(".name").text());
                    $(".txtTel").val($(this).find(".phone").text());
                    $(".hdUserId").val($(this).find(".userId").text());
                    $(".txtIDCard").val($(this).attr("data-id"));
                    $(".txtAddress").val($(this).attr("data-address"));
                    $(".txtEmail").val($(this).attr("data-Email"));
                    $(".txtCertificateType").val($(this).attr("data-CertificateType"));
                    //if ($(this).attr("data-grade") > 0) {
                    //    $("#GradeName").val($(this).attr("data-name"));
                    //    $("#UserGrade").val($(this).attr("data-grade"));
                    //} else {
                    //    $("#GradeName").val("还没有选择账户级别");
                    //}
                    $(".errorUserId").text("");
                    //ajax
                    $.getJSON("../Handler/FinancialOrder.ashx", { type: 19, UserId: $(this).find(".userId").text(), _: Math.random() }, function (result) {
                        if (result.Status) {
                            $(".txtPayBank").val(result.Data.PayBank);
                            $(".txtDepositBank").val(result.Data.DepositBank);
                            $(".txtRecAccName").val(result.Data.RecAccName);
                            $(".txtRecAccNum ").val(result.Data.RecAccNum);
                        }
                    });


                    $.getJSON("../Handler/FinaUserEmgyHandler.ashx",
                       { type: 0, UserId: $(this).find(".userId").text(), _: Math.random() },
                       function (result) {
                           if (result.Status) {
                               serializer.DeSerializeToSpan($("#title_fold_next"), result.Data);
                               var value = false;
                               $("#title_fold_next [data-name]").each(function (index, item) {
                                   if ($(this).text() == "") {
                                       value = true;
                                       alert("紧急联系人信息不完整，需要补填！");
                                       location.href = "FinancialUserInfo.aspx?css=1021&id=" + userId;
                                   }
                               });
                           }
                           else {
                               $("#title_fold_next [data-name]").text("");
                               alert(result.Message);
                               location.href = "FinancialUserInfo.aspx?css=1021&id=" + userId;
                           }
                       });
                });

            }
        });
});
$(".btnShow").bind("click", function () {
    $(".txtName").val($(".txtUserName").val());
})


//可绑定年度产品订单-详情查询
$(".btnSearchProduct").click(function () {
    $(".amountInfo").empty();
    var $OrderId = $(".txtOrderId").val();
    var $ProductName = $(".txtProductName").val();
    $.getJSON("../Handler/FinancialOrder.ashx",
        { OrderId: $OrderId, ProductTypeId: $ProductName, type: 27, _: Math.random() },
        function (result) {
            if (result.Status) {
                $(result.Data).each(function (index, item) {
                    $("#ProductTemplete").tmpl(item).appendTo($(".amountInfo"));
                });
            }
        })
})
//所关联订单跳点收益
$(".btnJumpProfitOrder").bind("click", function () {
    $(".jumpprofitorderinfo").empty();
    var UserId = $(".hdUserId").val();
    var $OrderId = $(".OrderId").val();
    if (!$OrderId) {
        $OrderId = $(".NewOrderId").val();
    }
    $.ajax({
        url: "../Handler/FinancialOrder.ashx",
        type: "post",
        data: { "UserId": UserId, type: 34, "OrderId": $OrderId, _: Math.random() },
        dataType: 'json',
        cache: false,
        success: function (result) {
            if (result.Status) {
                $(result.Data).each(function (index, item) {
                    $("#JumpProfitOrderTemplete").tmpl(item).appendTo($(".jumpprofitorderinfo"));
                });
            }
            else {
            }
        }
    });
})
//验证码校验
function validateCode() {
    var result = 0;
    $.ajax({
        type: "post",
        url: "../Handler/SMSHandler.ashx",
        dataType: "json",
        async: false,
        data: {
            type: 12,
            Phone: $(".txtTel").val(),
            UserId: $(".hdUserId").val(),
            Captcha: $(".txtCaptcha ").val()
        },
        cache: false,
        complete: function () {
        },
        success: function (data) {
            result = data;
        }
    });
    return result;
}
//上传参数
function getFormData() {
    return [{ name: "type", value: 0 }, { name: "OrderId", value: $(".OrderId").val() }];
}
//上传
$(".btn_upload").click(function () { $("#fileupload").click() });
$('#fileupload').fileupload({
    dataType: 'json',
    //limitMultiFileUploadSizeOverhead: 512,
    //limitMultiFileUploads: 2,
    sequentialUploads: true,
    formData: getFormData,
    add: function (e, data) {
        if (!validateFile(data.files)) {
            return false;
        }
        $.each(data.files, function (index, file) {
            var object = [{ Name: file.name, Size: (file.size / 1024).toFixed(2), Src: getObjectURL(file) }];
            $("#uploadTemplate").tmpl(object).appendTo(".uploadlist");
        });
        data.submit();
    },
    submit: function (e, data) { $(".uploadmsg").show(); },
    progress: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $(".uploadlist tr:contains(" + data.files[0].name + ") .bar").css('width', progress + '%');
        $(".uploadmsg").css("display", "block");
    },
    progressall: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $("#totalbar").css('width', progress + '%');
    },
    done: function (e, data) {
        if (data.result.Status) {
            $("#completeTemplate").tmpl(data.result.Data).appendTo(".completelist");
            bindDeleteFileEvent();
            $(".submit").show();
            $.each(data.files, function (index, file) {
                $(".uploadlist tr:contains(" + file.name + ") td:eq(4)").html("已完成");
                $(".uploadlist tr:contains(" + file.name + ") td:last").empty();
            });
        } else {
            alert(data.result.Data.Message);
        }
    },
    stop: function (e, data) {
        $(".uploadlist").empty();
        $("#totalbar").css('width', '0%');
        $(".uploadmsg").hide();
        $(".progressBar").text("100%").css("width", "100%");
    }
});
//添加删除图片事件 
function bindDeleteFileEvent() {
    $(".completelist").find(":button").unbind("click").click(function () {
        if (confirm("确定要删除？")) {
            var $imgId = $(this).attr("href");
            var $that = $(this);
            $.getJSON(
                "../Handler/FileHandler.ashx",
                { type: 1, FileId: $imgId, OrderId: $(".OrderId").val(), _: Math.random() },
                function (result) {
                    if (result.Status) {
                        $that.parents("tr").remove();
                        var count = $(".completelist tr[id]").length;
                        if (count == 0) {
                            $(".progressBar").text(50 + "%").css("width", 50 + "%");
                            $(".submit").hide();
                        }
                    }
                    else {
                        alert(result.Message);
                    }
                });
        }
    });
}

//对上传文件进行验证
function validateFile(files) {
    var result = true;
    $.each(files, function (index, file) {
        if (!/.(gif|jpg|jpeg|png|tif)$/.test(file.name.toLowerCase())) {
            alert("图片类型必须是.gif,jpeg,jpg,png,tif中的一种");
            result = false;
            return false;
        }
        if (file.size > 500 * 1024) {
            alert("文件大小不能超过500KB！");
            result = false;
            return false;
        }
    });
    return result;
}
//获取本地文件路径
function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}
//点击手续上传时绑定上传文件列表
$("li:contains('手续上传')").click(function () {
    //编辑模式且列表为空时加载数据
    var $Id = $(".OrderId").val();
    if ($Id) {
        if (!$(".completelist tr")[0]) {
            $.post(
                "../Handler/FileHandler.ashx",
                { type: 2, OrderId: $Id },
                function (files) {
                    if (files != "" && files != null) {
                        $(".completelist").empty();
                        $("#completeTemplate").tmpl(files).appendTo(".completelist");
                        bindDeleteFileEvent();
                    }
                });
        }
    }
    else {
        alert("请先完善项目信息！");
        setTimeout(function () {
            $("li:contains('项目建立')").click();
        }, 100);
    }
});
//发送验证码
$(".btnSendCaptcha").bind("click", function () {
    var $userId = $(".hdUserId").val();
    var $phone = $(".txtTel").val();
    var $idCard = $(".txtIDCard").val();
    if ($userId == null || $userId == "") {
        $(".btnShow").click();
        return false;
    }
    if (!/^\d{11}$/.test($phone)) {
        $(".errorTel").text("请输入11位有效的手机号码");
        return false;
    }
    var validate = new Validate();
    var msg = new Array("验证通过", "非法身份证号", "非法地区", "非法生日");
    var i = validate.CheckIdCard($(".txtIDCard").val());
    if (i < 0) {
        $(".txtIDCard").focus();
        $(".errorIDCard").text(msg[Math.abs(i)]);
        return;
    }
    $(this).attr("disabled", "disabled");
    $.getJSON("../Handler/FinancialOrder.ashx", { UserId: $userId, Phone: $phone, IdCard: $idCard, type: 15, _: Math.random() }, function (result) {
        if (result.Status) {
            startTimer();
        }
        else {
            $(".btnSendCaptcha").removeAttr("disabled");
        }
        alert(result.Message);
    });
});
//计时器
function startTimer() {
    var text = $(".btnSendCaptcha").text();
    var reg = new RegExp(/\d+$/);
    $(".btnSendCaptcha").attr("disabled", "disabled").text(text + 120);
    var timer = setInterval(function () {
        var time = parseInt(reg.exec($(".btnSendCaptcha").text()));
        time--;
        if (time <= 0) {
            $(".btnSendCaptcha").text(text).removeAttr("disabled");
            window.clearInterval(timer);
        }
        else {
            $(".btnSendCaptcha").text(text + time);
        }
    }, 1000);
}


//选择产品带出相应信息，如年化收益、封闭期
$(".ddlFProduct").change(function () {
    var product = new Product();
    var entity = product.GetInfoById($(this).val());
    if (entity != null) {
        $(".txtIncome").val(entity.YearRebate);
        $(".txtTerm").val(entity.ClosePeriod);
        if (entity.FinancialMode == 1) {
            //$(".lblEndDate").html("封闭结束日期：");
            $(".errorInitialLoanDate").html("封闭期满后自动续投支持随时赎回");
        }
        else {
            //$(".lblEndDate").html("合同结束日期：");
            $(".errorInitialLoanDate").text("");
        }
    }
    else {
        $(".txtIncome").val("");
        $(".txtTerm").val("");
    }

});

//当选择开始日期后，通过封闭期自动带出封闭结算期或者合同结束期
$(".txtContractStartDate").change(function () {

    var startDate = $(this).val();
    var monthDiff = parseInt($(".txtTerm").val());
    if (!isNaN(monthDiff)) {
        var date = addMonth(startDate, monthDiff);
        var endDate = subDay(date);
        $(".txtContractEndDate").val(endDate);
        $(".dtpContractEndDate").val(endDate.replace(/\//g, "-"));
    }
    else {
        $(this).val("");
        $(".dtpContractStartDate").val("");
        alert("请先选择理财产品");
    }
});





/*
 * date:当前日期,格式:yyyy/MM/dd(如:2011/09/26 2011/9/9)
 * months:要添加的月数
 * return:返回结果,格式:yyyy/MM/dd
 */
function addMonth(sDate, num) {

    var aYmd = sDate.split('/');
    var dt = new Date(aYmd[0], aYmd[1] - 1, aYmd[2]);
    dt.setMonth(dt.getMonth() + num);
    var y = dt.getFullYear();
    var m = dt.getMonth();
    var d = dt.getDate();
    //月份是从0开始啊！！！！
    m++;
    //if (m == 0) { m = 12; y = y - 1; }
    if (m < 10) m = '0' + m;
    if (d < 10) d = '0' + d;
    return y + '/' + m + '/' + d;
}
function subDay(sDate) {
    var dt = new Date(sDate);
    dt.setDate(dt.getDate() - 1);
    var y = dt.getFullYear();
    var m = dt.getMonth();
    var d = dt.getDate();
    //月份是从0开始啊！！！！
    m++;
    if (m < 10) m = '0' + m;
    if (d < 10) d = '0' + d;
    return y + '/' + m + '/' + d;
}